<template>
	<el-checkbox-group ref="checkboxGroupRef" :disabled="_disabled" :max="_max" :min="_min" :size="_size" v-bind="$attrs" @change="modelValueChanged">
		<el-space :alignment="_alignment" :direction="_direction" :size="_spacingSize">
			<el-checkbox v-for="item in options" :key="item.value" :border="_border" :disabled="item.disabled" :value="item.value">
				{{ item.label }}
			</el-checkbox>
		</el-space>
	</el-checkbox-group>
</template>

<script lang="ts" setup>

import {computed, ref} from 'vue'
import type {CheckboxGroupInstance} from 'element-plus'
import type * as CSS from 'csstype'
import {getBusinessCodeData} from '@/utils/commonUtil'

interface Props {
	codeType: string
	hideValue?: boolean
	disabled?: boolean
	disabledValueArray?: BusinessCodeTreeNode['value'][]
	border?: boolean
	min?: number
	max?: number
	size?: 'large' | 'default' | 'small'
	forceStringValue?: boolean
	direction?: 'horizontal' | 'vertical'
	alignment?: CSS.Property.AlignItems
	spacingSize?: 'default' | 'small' | 'large' | number | [number, number]
}

interface OptionItem {
	label: string
	value: BusinessCodeRadioValue
	disabled: boolean
}

const props = withDefaults(defineProps<Props>(), {
	hideValue: true,
	disabled: false,
	disabledValueArray: () => [],
	border: false,
	forceStringValue: false,
	size: 'default',
	direction: 'horizontal',
	alignment: 'center',
	spacingSize: 'default'
})

const emits = defineEmits<{
	(e: 'update:modelValue', value?: BusinessCodeCheckBoxValue): void
}>()

const _disabled = computed(() => props.disabled)
const _size = computed(() => props.size)
const _border = computed(() => props.border)
const _direction = computed(() => props.direction)
const _alignment = computed(() => props.alignment)
const _spacingSize = computed(() => props.spacingSize)
const _min = computed(() => props.min)
const _max = computed(() => props.max)

const checkboxGroupRef = ref<CheckboxGroupInstance>()

const options = computed<OptionItem[]>(() => {
	const options: OptionItem[] = []
	const businessCodeData = getBusinessCodeData(props.codeType)
	if (businessCodeData && businessCodeData.length > 0) {
		for (const businessCode of businessCodeData) {
			options.push({
				label: props.hideValue ? businessCode.label : `${businessCode.value} : ${businessCode.label}`,
				value: props.forceStringValue ? businessCode.value : handleValue(businessCode.value),
				disabled: props.disabledValueArray.includes(businessCode.value)
			})
		}
	}
	return options
})

const handleValue = (value: string): BusinessCodeRadioValue => {
	const numberValue = Number(value)
	if (Number.isSafeInteger(numberValue)) {
		return numberValue
	} else {
		return value
	}
}

// 向父组件传值
const modelValueChanged = (value: BusinessCodeCheckBoxValue) => {
	emits('update:modelValue', value)
}

</script>

<style lang="scss" scoped>

</style>
